<template>
  <div class="progress" ref="progress"
       @touchstart='touchStart'
       @touchmove='touchMove'
       @touchend='touchEnd'>
    <span class="buffered" ref="buffered"></span>
    <span class="line" ref="line"></span>
    <span class="circle" ref="circle"></span>
  </div>
</template>

<script type="text/ecmascript-6">
  export default{
    props: {
      percent: Number,
      buffered: Number,
      fullScreen: false
    },
    created() {
      this.touch = {}
    },
    methods: {
      setWidth(offsetWidth) {
        this.$refs.circle.style.transform = `translate3d(${offsetWidth}px,0,0)`
        this.$refs.line.style.width = `${offsetWidth}px`
      },
      touchStart(e) {
        this.touch.initiated = true
        this.touch.moved = false
        const touch = e.touches[0]
        this.touch.startX = touch.pageX
        this.touch.left = this.$refs.line.clientWidth || 0
        this.touch.max = this.$refs.progress.clientWidth
      },
      touchMove(e) {
        const touch = e.touches[0]
        const deltaX = touch.pageX - this.touch.startX
        if (!this.touch.moved) {
          this.touch.moved = true
        }
        let left = this.touch.left + deltaX
        let percent = left / this.touch.max
        if (percent >= 1) {
          percent = 1
        } else if (percent <= 0) {
          percent = 0
        }
        const circleWidth = this.$refs.circle.clientWidth
        const progressWidth = this.$refs.progress.clientWidth
        const offsetWidth = percent * (progressWidth - circleWidth)
        this.setWidth(offsetWidth)
      },
      touchEnd() {
        if (!this.touch.moved) {
          return
        }
        this.touch.initiated = false
        const circleWidth = this.$refs.circle.clientWidth
        const lineWidth = this.$refs.line.clientWidth
        const percent = lineWidth / (this.$refs.progress.clientWidth - circleWidth)
        this.$emit('percentChange', percent)
      }
    },
    watch: {
      percent(newPercent) {
        if (this.fullScreen && newPercent >= 0) {
          const circleWidth = this.$refs.circle.clientWidth
          const progressWidth = this.$refs.progress.clientWidth
          if (!this.touch.initiated) {
            const offsetWidth = newPercent * (progressWidth - circleWidth)
            this.setWidth(offsetWidth)
          }
        }
      },
      buffered(newBuffered) {
        if (newBuffered >= 1) {
          newBuffered = 1
        }
        this.$refs.buffered.style.width = `${newBuffered * 100}%`
      }
    }
  }
</script>

<style>

</style>
